'use strict'

const BaseService = require('./base')

class DistrictService extends BaseService {
  constructor(ctx) {
    super(ctx, 'District')
  }

  async tree(where) {
    console.log('where',where)
    const list = await this.ctx.model[this.modelName].findAll({
      where,
      order: this.listOrder()
    })
    return this.formatTree(list)
  }

  formatTree(list) {
    const map = {}
    const result = []

    list.forEach(item => {
      map[item.id] = {
        ...item.dataValues,
      }
    })

    list.forEach(item => {
      const node = map[item.id]
      if (item.parent_id === null) {
        result.push(node)
      } else {
        if (map[item.parent_id]) {
          if (!map[item.parent_id].children) {
            map[item.parent_id].children = []
          }
          map[item.parent_id].children.push(node)
        }
      }
    })

    return result
  }

  async deleteById(id) {
    const district = await this.ctx.model[this.modelName].findByPk(id)
    if (!district) {
      this.ctx.throw(404, '区域不存在')
    }
    await district.destroy()
    await this.ctx.model[this.modelName].destroy({ where: { parent_id: id } })
    return true
  }

  listOrder() {
    return [['create_time', 'DESC']]
  }
}

module.exports = DistrictService
